<template>
  <div class="app-container">
    <ContentWrap>
      <el-row :gutter="20">
        <el-col :span="4">
          <RegionTree ref="refDfqRegionTree" nodeType="1" :node-click="handleNodeClick"/>
        </el-col>

        <el-col :span="20" class="content-container">
          <div style="margin-bottom: 5px;">
            <span style="font-size: 22px;">历史冻结数据</span>（当前区域：<span
            style="color: #1890ff;">{{ editingZone ? editingZone.areaName : '无' }}）</span>
          </div>

          <el-table v-loading="loading" :data="dfqFreezeDataList" border size="mini" :height="228">
            <el-table-column type="index" width="35" align="center" label="#"/>
            <el-table-column label="名称" align="center">
              <template>
                {{ editingZone ? editingZone.areaName : '' }}
              </template>
            </el-table-column>
            <el-table-column label="日期" align="center" prop="freezetime"/>
            <el-table-column label="供水量(m³)" align="center" prop="inputFlow" sortable/>
            <el-table-column label="环比(%)" align="center" prop="hb" sortable>
              <template slot-scope="scope">
                <span v-if="parseFloat(scope.row.hb)<0" style="color: red;">{{ scope.row.hb }}</span>
                <span v-else style="color: green;">{{ scope.row.hb }}</span>
              </template>
            </el-table-column>
            <el-table-column label="售水量(m³)" align="center" prop="saleWater" sortable/>
            <el-table-column label="无收益水量(m³)" align="center" prop="freeWater" sortable/>
            <el-table-column label="产销差率(%)" align="center" prop="cxcl" sortable/>
            <el-table-column label="平均水压(MPa)" align="center" prop="avgPressure" sortable/>
          </el-table>

          <pagination :total="total"
                      :page.sync="queryParams.pageNum"
                      :limit.sync="queryParams.pageSize"
                      @pagination="getList"
                      size="mini"
                      layout="total, prev, pager, next, jumper"
          />

          <el-tabs v-model="activeName" @tab-click="handleClick">
            <div class="option-tool">
              <div>
                <!--              当前区域：<span style="color: #1890ff;">{{ editingZone ? editingZone.areaName : '无' }}</span>-->
              </div>
              <div>
                <el-date-picker v-model="wsmQueryDate"
                                v-if="activeName==='1' || activeName==='5'"
                                size="mini"
                                type="daterange"
                                value-format="yyyy-MM-dd"
                                style="width: 210px;"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                @change="handleQueryDateChange">
                </el-date-picker>

                <el-date-picker v-model="wpsQueryDate"
                                v-if="activeName==='2' || activeName==='3'"
                                size="mini"
                                type="monthrange"
                                value-format="yyyy-MM"
                                style="width: 210px;"
                                range-separator="至"
                                start-placeholder="开始月份"
                                end-placeholder="结束月份"
                                @change="handleQueryDateChange">
                </el-date-picker>

                <el-date-picker v-model="wbaQueryDate"
                                v-if="activeName==='4'"
                                size="mini"
                                type="month"
                                value-format="yyyy-MM"
                                style="width: 110px;"
                                placeholder="选择月份">
                </el-date-picker>
              </div>
            </div>

            <el-tab-pane label="供水数据监测" name="1">
              <WaterSupplyMonitor ref="refWaterSupplyMonitor"/>
            </el-tab-pane>

            <el-tab-pane label="产销差分析" name="2" :lazy="true">
              <WaterProdsaleRate ref="refWaterProdsaleRate"/>
            </el-tab-pane>

            <el-tab-pane label="供水量统计" name="3" :lazy="true">
              <WaterSupplyStatistics ref="refWaterSupplyStatistics"/>
            </el-tab-pane>

            <el-tab-pane label="水平衡分析" name="4" :lazy="true">
              <WaterBalanceAnalysis ref="refWaterBalanceAnalysis"/>
            </el-tab-pane>

            <el-tab-pane label="报警信息" name="5" :lazy="true">
              <el-table v-loading="warnLoading" :data="dfqWarnDataList" border size="mini" :height="getWarnHeight"
                        style="margin-top: 10px;">
                <el-table-column type="index" width="35" align="center" label="#"/>
                <el-table-column label="报警时间" align="center" prop="startTime" width="180">
                  <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.StartTime, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <!--              <el-table-column label="名称" align="center" prop="targetName"/>-->
                <el-table-column label="报警状态" align="center" prop="warnStatus">
                  <template slot-scope="scope">
                    <dict-tag :options="dict.type.warn_status" :value="scope.row.warnStatus"/>
                  </template>
                </el-table-column>
                <el-table-column label="报警参数" align="center" prop="warnParamType">
                  <template slot-scope="scope">
                    <dict-tag :options="dict.type.warn_param_type" :value="scope.row.warnParamType"/>
                  </template>
                </el-table-column>
                <el-table-column label="报警类型" align="center" prop="warnType">
                  <template slot-scope="scope">
                    <dict-tag :options="dict.type.warn_type" :value="scope.row.warnType"/>
                  </template>
                </el-table-column>
                <el-table-column label="报警值" align="center" prop="warnValue"/>
                <el-table-column label="参考值" align="center" prop="referenceValue"/>
                <el-table-column label="差值" align="center" prop="value"/>
              </el-table>

              <pagination :total="warnTotal"
                          :page.sync="warnQueryParams.pageNum"
                          :limit.sync="warnQueryParams.pageSize"
                          @pagination="getWarnDataList"
                          size="mini"
                          layout="total, sizes, prev, pager, next, jumper"
              />
            </el-tab-pane>

            <el-tab-pane label="基础信息" name="6" :lazy="true">
              <div style="width: 100%;margin-top: 10px;display: flex;justify-content: space-between;"
                   v-if="activeName==='6'">
                <div style="width: 58%;" :style="getMapHeight">
                  <drawregion @mapLoaded="handleMapLoaded" :drawable="false" ref="refDrawRegion"
                              style="border: 1px solid #E3E3E3;"/>
                </div>

                <div style="width: calc(42% - 10px);">
                  <el-descriptions class="margin-top" :column="1" border>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-user"></i>
                        上级区域
                      </template>
                      {{ editingZone ? getZoneName(editingZone.pid) : '' }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-location-outline"></i>
                        分区类型
                      </template>
                      <el-tag size="small">大分区</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-mobile-phone"></i>
                        分区名称
                      </template>
                      {{ editingZone ? editingZone.areaName : '' }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-tickets"></i>
                        抄表频率（月/次）
                      </template>
                      {{ dfqTagInfo ? dfqTagInfo.readFrequent : '' }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-tickets"></i>
                        抄表日期（1-28）
                      </template>
                      {{ dfqTagInfo ? dfqTagInfo.readDate : '' }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-office-building"></i>
                        日平均供水时长（小时）
                      </template>
                      {{ dfqTagInfo ? dfqTagInfo.supplyTime : '' }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-office-building"></i>
                        目标漏损率（%）
                      </template>
                      {{ dfqTagInfo ? dfqTagInfo.lsl : '' }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-office-building"></i>
                        目标产销差率（%）
                      </template>
                      {{ dfqTagInfo ? dfqTagInfo.cxcl : '' }}
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </ContentWrap>
  </div>
</template>

<script>
import moment from 'moment'
import RegionTree from "@/views/leakage/components/RegionTree.vue";
import WaterSupplyMonitor from '../components/WaterSupplyMonitor.vue'
import WaterProdsaleRate from '../components/WaterProdsaleRate.vue'
import WaterBalanceAnalysis from '../components/WaterBalanceAnalysis.vue'
import WaterSupplyStatistics from '../components/WaterSupplyStatistics.vue'
import {getZoneTagByAreaId} from '@/api/leakage/zoneTag'
import drawregion from "@/components/L7Maps/drawregion.vue";
import {getZoneWaterBalance} from "@/api/leakage/zoneBalanceFix";
import {getDfqDmaSupplyMonitorData} from '@/api/leakage/terminalHistoryData';
import {listFreezeDfq, getDfqProdsaleAnalysisData, getDfqSupplyAnalysisData} from "@/api/leakage/freezeDfq";
import {listWarnInfo} from '@/api/leakage/warnInfo'
import {getZoneJoinTerminals} from "@/api/leakage/zoneJoin";
import {Marker, MarkerLayer, Popup} from "@antv/l7";

export default {
  name: 'dfq',
  dicts: ['warn_handle_status', 'warn_param_type', 'warn_target_type', 'warn_status', 'warn_type'],
  components: {
    drawregion, RegionTree,
    WaterSupplyMonitor, WaterProdsaleRate,
    WaterBalanceAnalysis, WaterSupplyStatistics
  },
  data() {
    return {
      mapScene: undefined,
      screenHeight: null,
      activeName: '1',
      editingZone: undefined,
      dfqTagInfo: undefined,
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 5,
        areaid: null,
        frozenType: 'month'
      },
      // 实时数据采集（大）表格数据
      dfqFreezeDataList: [],
      wsmQueryDate: null,
      wpsQueryDate: null,
      wbaQueryDate: new moment().subtract(1, 'months').format('YYYY-MM'),
      // 遮罩层
      warnLoading: false,
      // 总条数
      warnTotal: 0,
      // 查询参数
      warnQueryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      dfqWarnDataList: [],
      terminalDataList: []
    }
  },
  methods: {
    handleMapLoaded(scene) {
      this.mapScene = scene
    },
    /** 查询实时数据采集（大）列表 */
    getList() {
      this.loading = true;
      listFreezeDfq(this.queryParams).then(res => {
        this.dfqFreezeDataList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
    loadMonitorTerminals() {
      getZoneJoinTerminals({areaId: this.editingZone.areaId, terminalMark: 1}).then((res => {
        this.terminalDataList = res.rows
        this.addTerminalMarkerToMap()
      }))
    },
    getWarnDataList() {
      this.warnLoading = true;
      this.warnQueryParams.targetID = this.editingZone.areaId
      this.warnQueryParams.targetType = 1
      listWarnInfo(this.warnQueryParams).then(res => {
        this.warnTotal = res.total;
        this.dfqWarnDataList = res.rows;
        this.warnLoading = false;
      });
    },
    handleNodeClick(node) {
      console.log(node)
      if (node.levelType !== '1') {
        this.editingZone = undefined
        this.$message.error('请选择大分区节点')
      } else {
        this.editingZone = node
        this.queryParams.areaid = node.areaId
        this.getList()
        this.loadTabPaneData()
      }
    },
    handleClick(tab, event) {
      this.loadTabPaneData()
    },
    resizeAllCharts() {
      this.$nextTick(() => {
        if (this.activeName === '1') {
          this.$refs.refWaterSupplyMonitor.resizeCharts(this.screenHeight)
        } else if (this.activeName === '2') {
          this.$refs.refWaterProdsaleRate.resizeCharts(this.screenHeight)
        } else if (this.activeName === '3') {
          this.$refs.refWaterSupplyStatistics.resizeCharts(this.screenHeight)
        } else if (this.activeName === '4') {
          this.$refs.refWaterBalanceAnalysis.resizeCharts(this.screenHeight)
        }
      })
    },
    loadTabPaneData() {
      const query = {
        areaId: this.editingZone.areaId,
      }
      if (this.activeName === '1') {
        if (this.wsmQueryDate) {
          query.queryDates = this.wsmQueryDate.join(",")
        }
        getDfqDmaSupplyMonitorData(query).then(res => {
          this.$refs.refWaterSupplyMonitor.updateOption(res.data)
        })
      } else if (this.activeName === '2') {
        if (this.wpsQueryDate) {
          query.queryDates = this.wpsQueryDate.join(",")
        }
        getDfqProdsaleAnalysisData(query).then(res => {
          this.$refs.refWaterProdsaleRate.updateOption(res.data)
        })
      } else if (this.activeName === '3') {
        if (this.wpsQueryDate) {
          query.queryDates = this.wpsQueryDate.join(",")
        }
        getDfqSupplyAnalysisData(query).then(res => {
          this.$refs.refWaterSupplyStatistics.updateOption(res.data)
        })
      } else if (this.activeName === '4') {
        getZoneWaterBalance({areaID: this.editingZone.areaId, paydate: this.wbaQueryDate}).then(res => {
          this.$refs.refWaterBalanceAnalysis.updateWaterBalanceFixedData(res.data)
        })
      } else if (this.activeName === '5') {
        this.getWarnDataList()
      } else if (this.activeName === '6') {
        setTimeout(() => {
          this.$refs.refDrawRegion.setShowDrawData(this.editingZone.zoom - 1, this.editingZone.areaPoint)
          this.loadMonitorTerminals()
        }, 1000)

        getZoneTagByAreaId({areaId: this.editingZone.areaId}).then(res => {
          this.dfqTagInfo = res.data
        })
      }
    },
    getZoneName(id) {
      return this.$refs.refDfqRegionTree.getZoneName(id)
    },
    handleQueryDateChange() {
      this.loadTabPaneData()
    },
    addTerminalMarkerToMap() {
      const that = this
      const terminals = this.terminalDataList.filter(item => item.lat != null && item.lng != null)
      let point
      terminals.forEach(t => {
        point = [parseFloat(t.lng), parseFloat(t.lat)]

        let markerIcon = t.used === '3' ? `/images/outlet.png` : `/images/inlet.png`
        const markerContent = `<div><img src="${markerIcon}" style="width: 40px;height: 40px;"></div>`
        let el = document.createElement('div')
        el.innerHTML = markerContent
        const marker = new Marker({element: el, draggable: false, offsets: [0, 0]}).setLnglat({
          lng: parseFloat(t.lng),
          lat: parseFloat(t.lat)
        })

        const data = t.realtimeGatherData
        const popup = new Popup({
          title: `【${t.usedName}】：</span> ${t.terminalName}`,
          lngLat: {
            lng: parseFloat(t.lng),
            lat: parseFloat(t.lat)
          },
          offsets: [0, 40],
          closeButton: false,
          html: `<div>
                  <div>瞬时流量：${data && data.instantNumber != null ? '<span style="color: limegreen;">' + data.instantNumber + '</span> m³/h' : '<span style="color: red;">-<span>'}</div>
                  <div>累计流量：${data && data.totalFlow != null ? '<span style="color: limegreen;">' + data.totalFlow + '</span> m³' : '<span style="color: red;">-<span>'}</div>
                  <div>压&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;力：${data && data.pressure != null ? '<span style="color: limegreen;">' + data.pressure + '</span> MPa' : '<span style="color: red;">-<span>'}</div>
                  <div>信号强度：${data && data.terminalCSQ != null ? '<span style="color: limegreen;">' + data.terminalCSQ + '</span>' : '<span style="color: red;">-<span>'}</div>
                  <div>更新时间：${data && data.ReadDate != null ? '<span style="color: limegreen;">' + data.ReadDate + '</span>' : '<span style="color: red;">-<span>'}</div>
                </div>`,
        });
        marker.setPopup(popup)

        marker.on('mouseover', (e) => {
          marker.openPopup()
        })

        marker.on('mouseout', (e) => {
          marker.closePopup()
        })

        this.mapScene.addMarker(marker);
      })
    },
  },
  created() {
    this.screenHeight = document.body.clientHeight
    const areaId = this.$route.params && this.$route.params.areaId;
  },
  computed: {
    getWarnHeight() {
      return this.screenHeight - 580
    },
    getMapHeight() {
      const h = this.screenHeight - 500
      return {height: h + 'px'}
    }
  },
  mounted() {
    window.onresize = () => {
      this.screenHeight = document.body.clientHeight
      this.resizeAllCharts()
    }
    setTimeout(() => {
      // 处理首页传参跳转
      const id = this.$route.query.id
      if (id) {
        const node = this.$refs.refDfqRegionTree.getZoneNode(id + '')
        if (node) {
          this.handleNodeClick(node)
        }
      }
    }, 1000)
  }
}

</script>

<style scoped lang="scss">
.option-tool {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

::v-deep .l7-popup .l7-popup-content {
  position: relative;
  padding: 16px;
  font-size: 14px;
  color: #FFFFFF;
  background: #5e72af;
  border-radius: 3px;
  -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

::v-deep .l7-popup-anchor-bottom .l7-popup-tip {
  -webkit-align-self: center;
  -ms-flex-item-align: center;
  align-self: center;
  border-top-color: #5e72af;
  border-bottom: none;
}
</style>
